home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++
- Subject: Re: How best to handle constructor failure?
- Date: 8 Jan 1996 15:42:30 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Message-ID: <4cre16$9oh@dawn.mmm.com>
- References: <4c36gl$5e5@nnrp1.news.primenet.com> <4cimnp$hne@news1.panix.com>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Jeffrey O. Katz (off@panix.com) wrote:
-
- [snip]
-
- > Yes, using auto pointers will avoid memory leaks from un-destructed objects.
- > The problem, however, is how to alter the sequence of code existing OUTSIDE of
- > the constructor, based on the success or failure of the constructor.
-
- > In addition, we cannot use exceptions for a variety of reasons (e.g., some
- > functions must be exported from a DLL using a straight C or PASCAL calling
- > convention, and errors need to be handled by a calling application written in
- > another language), and, even if we could, it appears that we would still need
- > to use a longjmp() inside the try {...} in order to get out of the constructor so as
- > to be able to bypass the code that follows the constructor in the function. Using
- > longjmp(), an initializer method that is called seperately from the constructor,
- > or various "test" methods (a method that returns a success/failure value) makes
- > code kludgy and inelegant. I was wondering what the "correct" approach (if
- > there is such a thing) for handling the problem was.
-
- > To make the problem a little clearer, what we need to do is something like this:
-
- > int MyFunction (int n, float y, ...) {
- > MyClass mc(n);
- > int return_code;
- > if (constructor failed entirely) {
- > rc = STACK_OVERFLOW;
- > } else if (allocations internal to the constructor failed) {
- > rc = INSUFFICIENT_HEAP;
- > } else {
- > ... lots of code ...
- > rc = SUCCESS;
- > }
- > return rc;
- > // the implicitly called destructor will perform any needed cleanup
- > }
-
- In general, C++ code to be executed by another language must be completely
- wrapped in a try-block, with exceptions caught and reported in the manner
- appropriate to that language. I don't see why any C++ code cannot be
- wrapped in that way. For example:
- int MyFunction (int n, float y, ...) {
- int rc = SUCCESS;
- try {
- MyClass mc(n);
- ... lots of code ...
- } catch (bad_alloc) {
- rc = INSUFFICIENT_HEAP;
- } catch (...) {
- rc = SOME_OTHER_ERROR;
- }
- return rc;
- // the implicitly called destructor will perform any needed cleanup
- }
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-